using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.TroubleCommand;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.TroubleCommandHandlers
{
    /// <summary>
    /// 标记消息为已读的命令处理器
    /// </summary>
    public class MarkMessageAsReadCommandHandler : IRequestHandler<MarkMessageAsReadCommand, APIResult<bool>>
    {
        private readonly SqlSugarContext sugar;

        public MarkMessageAsReadCommandHandler(SqlSugarContext sugar)
        {
            this.sugar = sugar;
        }

        public async Task<APIResult<bool>> Handle(MarkMessageAsReadCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();
            try
            {
                // 更新消息的已读状态
                var updatedRows = await sugar.db.Updateable<ChatListItem>()
                    .SetColumns(x => new ChatListItem { HasRedDot = false })
                    .Where(x => x.ChatListItemID == request.MessageId)
                    .ExecuteCommandAsync();

                result.data = updatedRows > 0;
                result.Code = updatedRows > 0 ? APIEnum.操作成功 : APIEnum.操作失败;
                result.Msg = updatedRows > 0 ? "消息已标记为已读" : "标记消息已读失败，可能消息不存在";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"标记消息已读时发生异常: {ex.Message}");
                result.Code = APIEnum.操作失败;
                result.Msg = $"标记消息已读失败: {ex.Message}";
                result.data = false;
            }
            return result;
        }
    }
} 